
<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="员工名称" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="员工名称"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="启用状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="启用状态" clearable size="small">
          <el-option
            v-for="(dict,index) in statusOptions"
            :key="index"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form-item></el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-action="'user@createEmployee'"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleCreate({},'新建')"
        >新建
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="list" style="width: 100%;">
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="员工名称" align="center" prop="username" />
      <el-table-column label="所属企业" align="center" prop="merchant_name" />
      <!--      <el-table-column type="用户头像" width="50" align="center" prop="avatar" />-->
      <el-table-column label="启用状态" align="center">
        <template v-slot="scope">
          <el-switch
            v-model="scope.row.status"
            active-text="启用"
            inactive-text="禁用"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="2"
            @change="disOrEnable($event,scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="created_at" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template v-slot="scope">
          <el-button
            v-action="'user@updateEmployee'"
            size="mini"
            type="primary"
            @click="handleCreate(scope.row,'编辑')"
          >编辑</el-button>
          <el-button
            v-action="'user@delEmployee'"
            size="mini"
            type="danger"
            @click="delEmployee(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.limit" @pagination="getList" />
    <!-- 新增 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="form.id === undefined ? rules : updateRules" label-width="100px" class="demo-ruleForm">
        <el-row>
          <el-col :span="24">
            <el-form-item label="员工名称" prop="username">
              <el-input v-model="form.username" :disabled="form.id!==undefined" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="登录密码" prop="password">
              <el-input v-model="form.password" type="password" auto-complete="new-password" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="确认密码" prop="checkPass">
              <el-input v-model="form.checkPass" type="password" auto-complete="new-password" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="员工级别" prop="position">
              <el-select v-model="form.position" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="权限角色" prop="roles">
              <el-tree
                ref="tree"
                :data="roles"
                show-checkbox
                node-key="id"
                :check-strictly="true"
                :default-checked-keys="form.roles"
                default-expand-all
                :expand-on-click-node="false"
                :render-content="renderContent"
                @check-change="checkChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-row style="top: 30px;margin-bottom: 30px;text-align:center;">
            <el-col :span="24">
              <el-button type="primary" size="medium" @click="submitForm('form')">{{ title }}</el-button>
              <el-button size="medium" @click="open=false">取消</el-button>

            </el-col>
          </el-row>
        </el-row>
      </el-form>
    </el-dialog>
  </div>

</template>
<style>
.el-input__inner {
  width: 90%;
}
.el-input__suffix {
  right: 10%;
}
</style>
<script>
import { employeeList, myRoles, updateEmployee, delEmployee, switchEmployee, createEmployee } from '@/api/user'
export default {
  name: 'Index',
  data() {
    var checkPass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    var checkRoles = (rule, value, callback) => {
      if (this.$refs.tree.getCheckedKeys().length === 1) {
        this.form.roles = this.$refs.tree.getCheckedKeys()
        callback()
      } else if (this.$refs.tree.getCheckedKeys().length === 0) {
        callback(new Error('要选择一个角色'))
      } else {
        callback(new Error('只需要选择一个角色'))
      }
    }
    return {
      // 遮罩层
      loading: true,
      open: false,
      title: '',
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      roles: [],
      info: '',
      // 用户状态
      statusOptions: [
        { 'value': 1, 'label': '正常' },
        { 'value': 2, 'label': '禁用' }
      ],
      options: [{
        value: 1,
        label: '经理'
        }, {
          value: 2,
          label: '员工'
        }, {
          value: 3,
          label: '外部客户'
      }],
      // 查询参数
      queryParams: {
        page: 1,
        limit: 10,
        username: undefined,
        status: undefined
      },
      form: {},
      show: false,
      ids: [],
      updateRules: {
        username: [
          { required: true, message: '请输入员工名称', trigger: 'blur' }
        ],
        password: [
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        checkPass: [
          { validator: checkPass2, trigger: 'blur' }
        ],
        roles: [
          { required: true, validator: checkRoles }
        ]
      },
      rules: {
        username: [
          { required: true, message: '请输入员工名称', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        checkPass: [
          { required: true, validator: checkPass2, trigger: 'blur' }
        ],
        roles: [
          { required: true, validator: checkRoles }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    /** 详情 */
    detail(row) {
      // orderInfo({ orderId: row.orderId, type: 1 }).then(response => {
      //   if (response.code === 10000) {
      //     this.form = response.data
      //     this.show = true
      //   }
      // })
    },
    /** 打开 */
    handleCreate(row, title) {
      const that = this
      myRoles({}).then(response => {
        that.roles = response.data
        if (that.$refs['form']) {
          that.$refs['form'].clearValidate()
        }
        that.form = row || {}
        that.title = title
        that.open = true
      })
    },
    /** 查询清单列表 */
    getList() {
      this.loading = true
      // console.log(this.queryParams)
      employeeList(this.queryParams).then(response => {
        // console.log(response)
        this.list = response.data
        this.total = response.count
        this.loading = false
      })
    },
    checkChange(data, checked) {
      if (checked === true) {
        this.$refs.tree.setCheckedKeys([])
        this.$refs.tree.setChecked(data, true)
      }
    },
    /** 状态字典翻译 */
    statusFormat(row, column) {
      let status = row.status
      for (const d of this.statusOptions) {
        if (row.status === d.value) {
          status = d.label
          break
        }
      }
      return status
    },
    // 用户状态
    disOrEnable(v, row) {
      const that = this
      const data = {}
      data.status = v
      data.id = row.id
      switchEmployee(data).then(response => {
        // console.log(response)
        that.$message.success(response.message)
        that.getList()
      })
    },
    submitForm(formName) {
      const that = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!that.form.id) {
            createEmployee(that.form).then(response => {
              // console.log(response)
              that.$message.success(response.message)
              that.open = false
              that.getList()
            })
          } else {
            updateEmployee(that.form).then(response => {
              // console.log(response)
              that.$message.success(response.message)
              that.open = false
              that.getList()
            })
          }
        } else {
          return false
        }
      })
    },
    delEmployee(row) {
      const that = this
      that.$confirm('是否删除员工' + row.username, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        delEmployee({ id: row.id }).then(response => {
          that.$message.success(response.message)
          that.getList()
        })
      }).catch(() => {
      })
    },
    renderContent(h, { node, data, store }) {
      return (
        <span class='custom-tree-node'>
          <span>{data.role_name}</span>
        </span>)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        page: 1,
        limit: 10,
        username: undefined,
        status: undefined
      }
      this.handleQuery()
    },
    /** 选中的项 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.multiple = !selection.length
    }
  }
}
</script>

